package com.sy.cloud.guess.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.sy.cloud.guess.model.Gokguessnum;
import com.sy.cloud.guess.model.Heroset;
import com.sy.cloud.guess.model.JOrder;
import com.sy.common.model.Juejinuser;
import com.sy.common.persistence.QueryHelper;
import com.sy.common.service.*;
import com.sy.common.util.Funutil;
import com.sy.shiro.UsernameToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.impl.client.SystemDefaultCredentialsProvider;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by mac on 2017-10-23.
 */
@Controller
@RequestMapping("/trade")
@Slf4j
public class TradeController {

    @Resource
    private IDbService dbService;

    @Resource
    private IBaseService baseService;

    @Resource
    private ITestService testService;

//    @Resource
//    private ISetsService sets;
    @Resource
    private IAlgorithm algorithm;

    /**
     * 走势图数据
     * */
    @RequestMapping(value = "/trendchart",method = RequestMethod.GET)
    public
    @ResponseBody
    void index(HttpServletRequest request, HttpServletResponse response) throws Exception{
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        response.setLocale(new java.util.Locale("zh","CN"));
        QueryHelper queryHelper = new QueryHelper();
        queryHelper.setLimit(10);
        queryHelper.setOffset(0);
        String sql = "select sp_gokguess_num.*, sp_hero_set.name from sp_gokguess_num left join sp_hero_set on sp_gokguess_num.heroId = sp_hero_set.id limit 0,10";
        List<Object[]> goklist =  baseService.nativeQuery( sql );
        Gson gson=new Gson();
        String json=gson.toJson(goklist);
        log.info(json);
        response.getWriter().print(json);
//        return json;
    }
    /**
     * 英雄中奖结果设定
     * 每到设定的时间间隔，就运行一次，结果存在数据库里
     * 传入参数：期号
     */
    @RequestMapping(value = "/dealhero",method = RequestMethod.GET)
    public
    @ResponseBody
    String hero(HttpServletRequest request){
        String issue = testService.getMaxIssue().toString();
        SimpleDateFormat df = new SimpleDateFormat("MMdd");//设置日期格式
        String s1 = df.format(new Date());
        String s4 = "";

        if( issue.length() == 8 ){
            String s2 = issue.substring( 4,8 );
            Integer i3 = Integer.parseInt( s2 )+1;
            s4 =  s1 +  String.format("%04d", i3); // 生成新的issue
        }else{
            s4 = s1+"0001";
        }





        int max=10000;
        long result = 1;
        Random random = new Random();
        int s = random.nextInt(max);
        List<Heroset> herosetList = testService.getList();
        if( s <= herosetList.get(0).getPercent()*100 ){
            herosetList.get(0).getId();
        }else if( s > herosetList.get(0).getPercent()*100 && s <= (herosetList.get(0).getPercent()*100+herosetList.get(1).getPercent()*100) ){
            result = herosetList.get(1).getId();
        }else if( s >= 3648 && s < 5472){
            result = herosetList.get(2).getId();
        }else if( s >= 5472 && s < 6688 ){
            result = herosetList.get(3).getId();
        }else if( s >= 6688 && s < 7904 ){
            result = herosetList.get(4).getId();
        }else if( s >= 7904 && s < 8816 ){
            result = herosetList.get(5).getId();
        }else if( s >= 8816 && s < 9728 ){
            result = herosetList.get(6).getId();
        }else if( s >= 9728 && s < 9910 ){
            result = herosetList.get(7).getId();
        }else if( s >= 9910 && s < 10000 ){
            result = herosetList.get(8).getId();
        }
        // 获得英雄场的结果

        // 使用事物 更新 sp_juejin_order表里的status为0的订单
        //

//        Gokguessnum gokguessnum = new Gokguessnum();
        StringBuilder sb = new StringBuilder();
        // 查询是否
        sb.append("From Gokguessnum where issue = ");
        sb.append( s4 );
        log.info( sb.toString() );
        List<Gokguessnum> gokguessnums = baseService.listQuery( sb.toString(), Gokguessnum.class );
//        Gokguessnum gokguessnum = gokguessnums.get(0);
//        IAlgorithm algorithm = new Algorithm();
        Gokguessnum gokguessnum2 = algorithm.kongpancode("1");// 获得精确场的中奖结果


        gokguessnum2.setIssue( Integer.parseInt(s4) );// 期号
        gokguessnum2.setHeroId( (int)result );// 中奖的英雄，6选一

        // 更新订单表里的订单和缓存金额
        testService.updateGokguessnum( gokguessnum2 );
        return result+"";
    }


    /**
     *
     * 英雄场下注和精确场下注，下订单的接口
     */
    @RequestMapping(value = "/placeorder1",method = RequestMethod.GET)
    public
    @ResponseBody
    void placeorder1(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        response.setLocale(new java.util.Locale("zh","CN"));

        JSONObject resultObject = new JSONObject();
        // 获取用户信息
        Subject subject = SecurityUtils.getSubject();
        UsernameToken token = new UsernameToken();

        PrincipalCollection pr = subject.getPrincipals();
        if( pr != null )
        {
            Object o1 = pr.getPrimaryPrincipal();
            token = (UsernameToken)subject.getPrincipals().getPrimaryPrincipal();
            log.info( token.getPhone() );
        }

        Double sumamount = 0.0;// 下单的和

        // 先获取参数
        String para1 = request.getParameter("para");
        String[] source = para1.split("-");
        for( int i =0;i<source.length; i++ )
        {
            String[] detail = source[i].split(",");
            sumamount += Integer.parseInt(detail[1]);
        }


        // 查询用户的余额
        Double money = testService.getMoney( token.getPhone() );
        log.info("用户"+token.getPhone()+"的余额是"+money.toString());
        log.info("下单之和是"+sumamount.toString() );
        if( sumamount > money ){
            // 下单金额大于余额
            resultObject.put("status", "0");
            resultObject.put("message", "下单金额大于余额");
            response.getWriter().print( resultObject.toJSONString() );
            return;
        }


        List<Heroset> herosetList = new ArrayList<Heroset>();

        StringBuilder selectSql0 = new StringBuilder();
        selectSql0.append(" From Heroset u where type = 1");
        herosetList = baseService.listQuery( selectSql0.toString(), Heroset.class );
        int d = 0;


        Map<String,Double> odsMap = testService.probaSet("hero");
        for( int i =0;i<source.length; i++ )
        {
            String[] detail = source[i].split(",");
            sumamount += Integer.parseInt(detail[1]);
            JOrder order = new JOrder();
            order.setCreatetime( System.currentTimeMillis()/1000 + "" );


            order.setPhone( token.getPhone() );// 用户电话号码
            order.setUserid( token.getUserId() );// 用户id
            order.setAmount( Integer.parseInt( detail[1]) );// 下单金额
            order.setCapital( Integer.parseInt(detail[0]) );// 英雄的种类
            order.setIs_win( 0 );
            order.setGet_amount( Integer.parseInt(detail[1]) * odsMap.get( detail[0] ));// 赢了应该获得的金额
            order.setTrade_time(35); //默认35秒
            order.setType( 0 );
            if(testService.dealdb(order) ){
                resultObject.put("status", "1");
            }else{
                resultObject.put("status", "0");
                resultObject.put("message", "数据库错误");
            }
            response.getWriter().print( resultObject.toJSONString() );
            return;
        }
    }


    @RequestMapping(value = "/capitallist",method = RequestMethod.GET)
    public
    @ResponseBody
    void getlist3(HttpServletRequest request, HttpServletResponse response) throws Exception{
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        response.setLocale(new java.util.Locale("zh","CN"));
        Gson gson=new Gson();
        List<Object[]> allList = testService.getList3();
        String json=gson.toJson(allList);
        response.getWriter().print(json);
    }


    /**
     * 判断是否登录
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/iflogin",method = RequestMethod.GET)
    public
    @ResponseBody
    void getloginstatus(HttpServletRequest request, HttpServletResponse response) throws Exception{
        // 获取用户信息
        JSONObject jsonObject = new JSONObject();
        Subject subject = SecurityUtils.getSubject();
        PrincipalCollection pr = subject.getPrincipals();
        if( pr != null )
        {
            // 登录
            jsonObject.put("status","1");
            response.getWriter().print(jsonObject.toString());
        }else{
            // 没登录
            jsonObject.put("status","0");
            response.getWriter().print(jsonObject.toString());
        }
    }


    /**
     * 给出前端页面的倒计时
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/countdown",method = RequestMethod.GET)
    public
    @ResponseBody
    void getCountDown(HttpServletRequest request, HttpServletResponse response) throws Exception{
        String str = "select max(create_time) from sp_gokguess_num";
        List<Object[]> objectList = baseService.nativeQuery( str );
        Object object =  objectList.get(0);

        // object是上次计算的时间。
        double ob2 = Double.parseDouble( object.toString() ) + 30;

        double ob3 = ob2 - System.currentTimeMillis()/1000;

        response.getWriter().print( (int)ob3 );
    }

    /**
     * 给出前端页面的倒计时
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/countdown1",method = RequestMethod.GET)
    public
    @ResponseBody
    void getCountDown1(HttpServletRequest request, HttpServletResponse response) throws Exception{

        int ob3 = -31;
        response.getWriter().print( ob3 );
    }


    /**
     * test
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/test",method = RequestMethod.GET)
    public
    @ResponseBody
    void test(HttpServletRequest request, HttpServletResponse response) throws Exception{
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        System.out.println(df.format(new Date()));// new Date()为获取当前系统时间
        response.getWriter().print( df.format(new Date()) );
        response.getWriter().print( "\r\n" );
    }


    /**
     * 游戏结果
     */
    @RequestMapping(value = "/gameresult",method = RequestMethod.GET)
    public
    @ResponseBody
    void gameResult( HttpServletRequest request, HttpServletResponse response ){
        QueryHelper queryHelper = new QueryHelper();
        queryHelper.setOffset(0);
        queryHelper.setLimit(1);
        StringBuilder hql = new StringBuilder();
        hql.append( "From Gokguessnum order by create_time desc" );
        List< Gokguessnum > gokguessnumList = baseService.listQueryForPage( hql.toString(), Gokguessnum.class, queryHelper );


        Gokguessnum gokguessnum = gokguessnumList.get(0);
//        DecimalFormat df = new DecimalFormat("0");

        String jsonObject = JSONObject.toJSONString( gokguessnumList.get(0) );
        try {
            response.getWriter().print( jsonObject );
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 背包信息展示接口
     */
    @RequestMapping(value = "/knapsackdisplay",method = RequestMethod.GET)
    public
    @ResponseBody
    void knapsack( HttpServletRequest request, HttpServletResponse response  ) throws IOException {
        // 获取用户信息
        Subject subject = SecurityUtils.getSubject();
        UsernameToken token = new UsernameToken();

        PrincipalCollection pr = subject.getPrincipals();
        if( pr != null )
        {
            Object o1 = pr.getPrimaryPrincipal();
            token = (UsernameToken)subject.getPrincipals().getPrimaryPrincipal();
            log.info( token.getPhone() );
        }

        Juejinuser juejinuser = new Juejinuser();
        StringBuilder hql = new StringBuilder();
        hql.append("From Juejinuser where phone = ");
        hql.append( token.getPhone() );
        List< Juejinuser > juejinuserList = baseService.listQuery( hql.toString(), Juejinuser.class );
        juejinuser = juejinuserList.get(0);
        response.getWriter().print(juejinuser.getKnapsack());

    }

    /**
     * 背包 增加卡片
     */
    @RequestMapping(value = "/knapsackadd",method = RequestMethod.GET)
    public
    @ResponseBody
    String knapsackadd( HttpServletRequest request, HttpServletResponse response  ) throws IOException {
        String t0 = request.getParameter("type");
        Integer t1 = Integer.parseInt( t0 );
        Integer type = t1--;

        // 获取用户信息
        Subject subject = SecurityUtils.getSubject();
        UsernameToken token = new UsernameToken();


        PrincipalCollection pr = subject.getPrincipals();
        if( pr != null )
        {
            Object o1 = pr.getPrimaryPrincipal();
            token = (UsernameToken)subject.getPrincipals().getPrimaryPrincipal();
            log.info( token.getPhone() );
        }else {
            return "login";
        }

        Juejinuser juejinuser = new Juejinuser();
        StringBuilder hql = new StringBuilder();
        hql.append("From Juejinuser where phone = ");
        hql.append( token.getPhone() );
        List< Juejinuser > juejinuserList = baseService.listQuery( hql.toString(), Juejinuser.class );
        juejinuser = juejinuserList.get(0);
//        response.getWriter().print(juejinuser.getKnapsack());

        String s1 = juejinuser.getKnapsack();

        String s2 = s1.substring(type,type+1);
        Integer s3 = Integer.parseInt( s2 );
        s3++;

        String s4 = s1.substring(0,type);
        String s5 = s1.substring(type + 1);
        String s6 = s4 + s3.toString() + s5;


        juejinuser.setKnapsack( s6 );
        testService.updateUser(juejinuser);
        response.getWriter().print("success");
        return "index";
    }




    /**
     * 背包 减少卡片
     */
    @RequestMapping(value = "/knapsackdelete",method = RequestMethod.GET)
    public
    @ResponseBody
    void knapsackdelete( HttpServletRequest request, HttpServletResponse response  ) throws IOException {
        String t0 = request.getParameter("type");
        Integer t1 = Integer.parseInt( t0 );
        Integer type = t1--;

        // 获取用户信息
        Subject subject = SecurityUtils.getSubject();
        UsernameToken token = new UsernameToken();


        PrincipalCollection pr = subject.getPrincipals();
        if( pr != null )
        {
            Object o1 = pr.getPrimaryPrincipal();
            token = (UsernameToken)subject.getPrincipals().getPrimaryPrincipal();
            log.info( token.getPhone() );
        }

        Juejinuser juejinuser = new Juejinuser();
        StringBuilder hql = new StringBuilder();
        hql.append("From Juejinuser where phone = ");
        hql.append( token.getPhone() );
        List< Juejinuser > juejinuserList = baseService.listQuery( hql.toString(), Juejinuser.class );
        juejinuser = juejinuserList.get(0);
//        response.getWriter().print(juejinuser.getKnapsack());

        String s1 = juejinuser.getKnapsack();

        String s2 = s1.substring(type,type+1);
        Integer s3 = Integer.parseInt( s2 );
        if( s3 <=0 ){
            s3--;
        }else{
            response.getWriter().print("nocards");
        }


        String s4 = s1.substring(0,type);
        String s5 = s1.substring(type + 1);
        String s6 = s4 + s3.toString() + s5;


        juejinuser.setKnapsack( s6 );
        testService.updateUser(juejinuser);
        response.getWriter().print("success");
    }





}
